<?php
    class AdminDthink_UserController extends Main_Controller_Action
    {
        private $_arrParam;
        private $_model;

        public function init() {
            $this->loadTemplates('admin');
            $this->_arrParam = $this->_request->getParams();
            $this->_model = new AdminDthink_Model_User();
        }
        
        public function preDispatch() {
        	$auth = Zend_Auth::getInstance();
        	if(!$auth->hasIdentity()) {
        		if($this->_request->getActionName() != 'login') {
        			$this->_redirect('/admin-dthink/index/login');
        		}
        	}
        }
        
        public function indexAction() {
            $this->view->headTitle("Quản lý tài khoản");
            if($_POST['add']) {
                $this->_redirect('admin-dthink/user/create');
            }
            if($_POST['refresh']) {
                $this->_redirect('admin-dthink/user');
            }
            if($_POST['delete']) {
                $listId = $this->_arrParam['check'];
                $this->_model->deleteUsers($listId);
                $this->_redirect($_SERVER['HTTP_REFERER']);
            }

            $list = $this->_model->listUser();
            $adapter = new Zend_Paginator_Adapter_DbSelect($list);
            $paginator = new Zend_Paginator($adapter);
            $paginator->setItemCountPerPage(40);
            $paginator->setPageRange(5);
            $currentPage = $this->_request->getParam('page', 1);
            $paginator->setCurrentPageNumber($currentPage);
            
            $this->view->data = $paginator;
            $this->view->total = $paginator->getTotalItemCount();
        }
        
        public function createAction() {
            $this->view->headTitle("Thêm tài khoản mới");
            if($this->_request->isPost()) {
                $flex = new Zendvn_Filter_RemoveCircumflex();
                $upload = new Zend_File_Transfer_Adapter_Http();
                $upload->setDestination(PUBLIC_PATH . '/files/user');
                $info = $upload->getFileInfo();
                $avatar = $upload->getFileName('avatar', false);
                $filter = new Zend_Filter_StringTrim();
                $toLower = new Zend_Filter_StringToLower();
                $email      = (string) $toLower->filter($filter->filter($this->_arrParam['email']));
                $password   = (string) $this->_arrParam['password'];
                $rePassword = (string) $this->_arrParam['rePassword'];
                $level      = (int) $this->_arrParam['level'];
                $fullname   = (string) $filter->filter($this->_arrParam['fullname']);
                $gender     = (int) $this->_arrParam['gender'];
                $birthday   = $this->_arrParam['year'].'-'.$this->_arrParam['month'].'-'.$this->_arrParam['day'];
                $flag = true;
                
                $validation = new AdminDthink_Form_ValidateUser();
                if($validation->validEmail($email)) {
                    $this->view->emailValue = $email;
                }
                else {
                    $this->view->errorEmail = 'Địa chỉ email không hợp lệ';
                    $flag = false;
                }
                if($this->_model->checkUser($email) > 0) {
                    $this->view->errorEmail = 'Địa chỉ email này đã tồn tại';
                    $flag = false;
                }
                if(!$validation->validPassword($password)) {
                    $this->view->errorPassword = 'Mật khẩu yêu cầu từ 6-32 kí tự';
                    $flag = false;
                }
                if(!$validation->validPassword($rePassword)) {
                    $this->view->errorRePassword = 'Mật khẩu yêu cầu từ 6-32 kí tự';
                    $flag = false;
                }
                if($validation->validFullname($fullname)) {
                    $this->view->fullnameValue = $fullname;
                }
                else {
                    $this->view->errorFullname = 'Tên đầy đủ không hợp lệ';
                    $flag = false;
                }
                
                if($flag == true) {
                    if($password == $rePassword) {
                        $password = md5($password);
                        $code = time() . mt_rand(5, 99999999);
                        if(!$validation->validAvatar($avatar)) {
                            $data = array(
                                'email' => $email,
                                'password' => $password,
                                'avatar' => 0,
                                'fullname' => $fullname,
                                'gender' => $gender,
                                'birthday' => $birthday,
                                'level' => $level,
                                'status' => 1,
                                'code' => $code,
                                'fullname_plaintext' => $toLower->filter($flex->filter($fullname)),
                            );
                            $this->_model->createUser($data);
                            $this->_redirect('admin-dthink/user');
                        }
                        else {
                            $upload->addValidator('Size', false, 410000)
                                   ->addValidator('Extension', false, 'jpg,jpeg,png,gif');
                            if(!$upload->isValid()) {
                                    $this->view->errorAvatar = 'Ảnh phải đúng định dạng (jpeg, jpg, png, gif) và dung lượng tối đa 400KB';
                            }
                            else {
                                preg_match('#\.([^\.]+)$#', $avatar, $matches);
                                $fileExtension  = $matches[1];
                                $newFileName = 'pic_' . time() . mt_rand(5, 99999999) . '.' . $fileExtension;						

                                $options = array('target' => PUBLIC_PATH . '/files/user/' . $newFileName,'overwrite'=>true);
                                $upload->addFilter('Rename',$options,'avatar');
                                $upload->receive('avatar');

                                $data = array(
                                    'email' => $email,
                                    'password' => $password,
                                    'avatar' => $newFileName,
                                    'fullname' => $fullname,
                                    'gender' => $gender,
                                    'birthday' => $birthday,
                                    'level' => $level,
                                    'status' => 1,
                                    'code' => $code,
                                    'fullname_plaintext' => $toLower->filter($flex->filter($fullname)),
                                );
                                $this->_model->createUser($data);
                                $this->_redirect('admin-dthink/user');
                            }
                        }
                    }
                    else {
                        $this->view->error = 'Mật khẩu không trùng khớp';
                    }
                }
            }
        }
        
        public function editAction() {
            $this->view->headTitle('Sửa thông tin tài khoản');
            $user_id = (int) $this->_arrParam['user_id'];
            $this->view->data = $this->_model->getUserById($user_id);
            
            if($_POST['delImg']) {
                $this->_model->delImg($user_id);
                if (is_file(PUBLIC_PATH . '/files/user/' . $this->view->data['avatar'])) {
                    unlink(PUBLIC_PATH . '/files/user/' . $this->view->data['avatar']);
                }
                $this->view->error = 'Đã xóa ảnh thành công';
                $this->_redirect($_SERVER['HTTP_REFERER']);
            }
            
            if($_POST['submit']) {
                $filter = new Zend_Filter_StringTrim();
                $flex = new Zendvn_Filter_RemoveCircumflex();
                $toLower = new Zend_Filter_StringToLower();
                $password   = (string) $this->_arrParam['password'];
                $rePassword = (string) $this->_arrParam['rePassword'];
                $email      = (string) $toLower->filter($filter->filter($this->_arrParam['email']));
                $level      = (int) $this->_arrParam['level'];
                $status     = (int) $this->_arrParam['status'];
                $fullname   = (string) $filter->filter($this->_arrParam['fullname']);
                $gender     = (int) $this->_arrParam['gender'];
                $birthday   = $this->_arrParam['year'].'-'.$this->_arrParam['month'].'-'.$this->_arrParam['day'];
                $flag = true;
                
                $validation = new AdminDthink_Form_ValidateUser();
                if(!$validation->validEmail($email)) {
                    $this->view->errorEmail = 'Địa chỉ email không hợp lệ';
                    $flag = false;
                }
                if(!$validation->validFullname($fullname)) {
                    $this->view->errorFullname = 'Tên đầy đủ không hợp lệ';
                    $flag = false;
                }
                if($this->view->data['email'] != $email) {
                    if($this->_model->checkUser($email, $user_id) > 0) {
                        $this->view->errorEmail = 'Địa chỉ email này đã tồn tại';
                        $flag = false;
                    }
                }
                
                if($flag == true) {
                    $upload = new Zend_File_Transfer_Adapter_Http();
                    $upload->setDestination(PUBLIC_PATH . '/files/user');
                    $info = $upload->getFileInfo();
                    $avatar = $upload->getFileName('avatar', false);
                    
                    if(($password != '') or ($rePassword != '')) {
                        if(!$validation->validPassword($password)) {
                            $this->view->errorPassword = 'Mật khẩu phải từ 6-32 kí tự';
                            $flag = false;
                        }
                        if(!$validation->validPassword($rePassword)) {
                            $this->view->errorRePassword = 'Mật khẩu phải từ 6-32 kí tự';
                            $flag = false;
                        }
                        if($password != $rePassword) {
                            $this->view->error = 'Mật khẩu không trùng khớp';
                            $flag = false;
                        }
                        if($flag == true) {
                            $password = md5($password);
                            if(!$validation->validAvatar($avatar)) {
                                $data = array(
                                    'email' => $email,
                                    'password' => $password,
                                    'fullname' => $fullname,
                                    'gender' => $gender,
                                    'birthday' => $birthday,
                                    'level' => $level,
                                    'status' => $status,
                                    'fullname_plaintext' => $toLower->filter($flex->filter($fullname)),
                                );
                                $this->_model->editUser($data, $user_id);
                                $this->_redirect('admin-dthink/user');
                            }
                            else {
                                $upload->addValidator('Size', false, 410000)
                                       ->addValidator('Extension', false, 'jpg,jpeg,png,gif');
                                if(!$upload->isValid()) {
                                    $this->view->errorAvatar = 'Ảnh phải đúng định dạng (jpeg, jpg, png, gif) và dung lượng tối đa 400KB';
                                }
                                else {
                                    preg_match('#\.([^\.]+)$#', $avatar, $matches);
                                    $fileExtension  = $matches[1];
                                    $newFileName = 'pic_' . time() . mt_rand(5, 99999999) . '.' . $fileExtension;

                                    $options = array('target' => PUBLIC_PATH . '/files/user/' . $newFileName,'overwrite'=>true);
                                    $upload->addFilter('Rename',$options,'avatar');
                                    $upload->receive('avatar');
                                    
                                    $data = array(
                                        'email' => $email,
                                        'password' => $password,
                                        'avatar' => $newFileName,
                                        'fullname' => $fullname,
                                        'gender' => $gender,
                                        'birthday' => $birthday,
                                        'level' => $level,
                                        'status' => $status,
                                        'fullname_plaintext' => $toLower->filter($flex->filter($fullname)),
                                    );
                                    $this->_model->editUser($data, $user_id);
                                    if (is_file(PUBLIC_PATH . '/files/user/' . $this->view->data['avatar'])) {
                                        unlink(PUBLIC_PATH . '/files/user/' . $this->view->data['avatar']);
                                    }
                                    $this->_redirect('admin-dthink/user');
                                }
                            }
                        }
                    }
                    else {
                        if(!$validation->validAvatar($avatar)) {
                            $data = array(
                                'email' => $email,
                                'fullname' => $fullname,
                                'gender' => $gender,
                                'birthday' => $birthday,
                                'level' => $level,
                                'status' => $status,
                                'fullname_plaintext' => $toLower->filter($flex->filter($fullname)),
                            );
                            $this->_model->editUser($data, $user_id);
                            $this->_redirect('admin-dthink/user');
                        }
                        else {
                            $upload->addValidator('Size', false, 410000)
                                   ->addValidator('Extension', false, 'jpg,jpeg,png,gif');
                            if(!$upload->isValid()) {
                                $this->view->errorAvatar = 'Ảnh phải đúng định dạng (jpeg, jpg, png, gif) và dung lượng tối đa 400KB';
                            }
                            else {
                                preg_match('#\.([^\.]+)$#', $avatar, $matches);
                                $fileExtension  = $matches[1];
                                $newFileName = 'pic_' . time() . mt_rand(5, 99999999) . '.' . $fileExtension;

                                $options = array('target' => PUBLIC_PATH . '/files/user/' . $newFileName,'overwrite'=>true);
                                $upload->addFilter('Rename',$options,'avatar');
                                $upload->receive('avatar');
          			
                                $data = array(
                                    'email' => $email,
                                    'avatar' => $newFileName,
                                    'fullname' => $fullname,
                                    'gender' => $gender,
                                    'birthday' => $birthday,
                                    'level' => $level,
                                    'status' => $status,
                                    'fullname_plaintext' => $toLower->filter($flex->filter($fullname)),
                                );
                                $this->_model->editUser($data, $user_id);
                                if (is_file(PUBLIC_PATH . '/files/user/' . $this->view->data['avatar'])) {
                                    unlink(PUBLIC_PATH . '/files/user/' . $this->view->data['avatar']);
                                }
                                $this->_redirect('admin-dthink/user');
                            }
                        }
                    }
                }
            }
        }
        
        public function deleteAction() {
            $user_id = (int) $this->_arrParam['user_id'];
            $this->_model->deleteUser($user_id);
            $this->_redirect($_SERVER['HTTP_REFERER']);
        }
        
        public function publishAction() {
            $user_id = (int) $this->_arrParam['user_id'];
            $status = (int) $this->_arrParam['status'];
            $data = array();
            if($status == 0) {
                $data['status'] = 1;
            }
            else {
                $data['status'] = 0;
            }
            $this->_model->publishUser($data, $user_id);
            $this->_redirect($_SERVER['HTTP_REFERER']);
        }
        
        public function searchAction() {
            $this->view->headTitle('Tìm kiếm tài khoản');
            $filter = new Zend_Filter_StringTrim();
            $flex = new Zendvn_Filter_RemoveCircumflex();
            $toLower = new Zend_Filter_StringToLower();
            $keyword = (string) $filter->filter($this->_arrParam['keyword']);
            $this->view->searchvalue = $keyword;
            $keyword = $toLower->filter($flex->filter($keyword));
            $flag = true;

            if($_POST['add']) {
                $this->_redirect('admin-dthink/user/create');
            }
            if($_POST['refresh']) {
                $this->_redirect('admin-dthink/user');
            }
            if($_POST['delete']) {
                $listId = $this->_arrParam['check'];
                $result = $this->_model->deleteUsers($listId);
                $this->_redirect($_SERVER['HTTP_REFERER']);
            }

            $validation = new AdminDthink_Form_ValidateUser();
            if($validation->validSearch($keyword)) {
                $this->view->searchValue = $keyword;
            }
            else {
                $this->view->errorSearch = 'Từ tìm kiếm có độ dài từ 3-50 kí tự';
                $flag = false;
            }

            if($flag == true) {
                $result = $this->_model->searchUser($keyword);
                $adapter = new Zend_Paginator_Adapter_DbSelect($result);
                $paginator = new Zend_Paginator($adapter);
                $paginator->setItemCountPerPage(40);
                $paginator->setPageRange(5);
                $currentPage = $this->_request->getParam('page', 1);
                $paginator->setCurrentPageNumber($currentPage);

                $this->view->data = $paginator;
                $this->view->total = $paginator->getTotalItemCount();
            }
        }
        
        public function profileAction() {
            $this->view->headTitle('Thông tin tài khoản');
            $auth = Zend_Auth::getInstance();
            $infoUser = $auth->getIdentity();
            $user_id = $infoUser->user_id;
            $this->view->data = $this->_model->getUserById($user_id);
            
            if($_POST['delImg']) {
                $this->_model->delImg($user_id);
                if (is_file(PUBLIC_PATH . '/files/user/' . $this->view->data['avatar'])) {
                    unlink(PUBLIC_PATH . '/files/user/' . $this->view->data['avatar']);
                }
                $this->view->error = 'Đã xóa ảnh thành công';
                $this->_redirect($_SERVER['HTTP_REFERER']);
            }
            if($_POST['submit']) {
                $filter = new Zend_Filter_StringTrim();
                $flex = new Zendvn_Filter_RemoveCircumflex();
                $toLower = new Zend_Filter_StringToLower();
                $email      = (string) $this->view->data['email'];
                $fullname   = (string) $filter->filter($this->_arrParam['fullname']);
                $gender     = (int) $this->_arrParam['gender'];
                $birthday   = $this->_arrParam['year'].'-'.$this->_arrParam['month'].'-'.$this->_arrParam['day'];
                $flag = true;
                
                $validation = new AdminDthink_Form_ValidateUser();
                if(!$validation->validFullname($fullname)) {
                    $this->view->errorFullname = 'Tên đầy đủ không hợp lệ';
                    $flag = false;
                }
                
                if($flag == true) {
                    $upload = new Zend_File_Transfer_Adapter_Http();
                    $upload->setDestination(PUBLIC_PATH . '/files/user');
                    $info = $upload->getFileInfo();
                    $avatar = $upload->getFileName('avatar', false);
                    if(!$validation->validAvatar($avatar)) {
                        $data = array(
                            'email' => $email,
                            'fullname' => $fullname,
                            'gender' => $gender,
                            'birthday' => $birthday,
                            'fullname_plaintext' => $toLower->filter($flex->filter($fullname)),
                        );
                        $this->_model->editUser($data, $user_id);
                        $this->view->error = 'Đã sửa thành công';
                        $this->view->data = $this->_model->getUserById($user_id);
                    }
                    else {
                        $upload->addValidator('Size', false, 410000)
                               ->addValidator('Extension', false, 'jpg,jpeg,png,bmp,gif');
                        if(!$upload->isValid()) {
                            $this->view->errorAvatar = 'Ảnh phải đúng định dạng (jpeg, jpg, bmp, png, gif) và dung lượng tối đa 400KB';
                        }
                        else{
                            preg_match('#\.([^\.]+)$#', $avatar, $matches);
                            $fileExtension  = $matches[1];
                            $newFileName = 'pic_' . time() . mt_rand(5, 99999999) . '.' . $fileExtension;

                            $options = array('target' => PUBLIC_PATH . '/files/user/' . $newFileName,'overwrite'=>true);
                            $upload->addFilter('Rename',$options,'avatar');
                            $upload->receive('avatar');

                            $data = array(
                                'email' => $email,
                                'avatar' => $newFileName,
                                'fullname' => $fullname,
                                'gender' => $gender,
                                'birthday' => $birthday,
                                'fullname_plaintext' => $toLower->filter($flex->filter($fullname)),
                            );
                            $this->_model->editUser($data, $user_id);
                            if (is_file(PUBLIC_PATH . '/files/user/' . $this->view->data['avatar'])) {
                                unlink(PUBLIC_PATH . '/files/user/' . $this->view->data['avatar']);
                            }
                            $this->view->error = 'Đã sửa thành công';
                            $this->view->data = $this->_model->getUserById($user_id);
                        }
                    }
                }
            }
        }
        
        public function changepasswordAction() {
            $this->view->headTitle('Thay đổi mật khẩu');
            $validation = new AdminDthink_Form_ValidateUser();
        	
            if($this->_request->isPost()) {
                $oldPassword = (string) $this->_arrParam['oldPassword'];
                $password = (string) $this->_arrParam['password'];
                $rePassword = (string) $this->_arrParam['rePassword'];
                $flag = true;

                if($validation->validPassword($oldPassword)) {
                    $this->view->oldPasswordValue = $oldPassword;
                }
                else {
                    $this->view->errorOldPassword = 'Mật khẩu yêu cầu từ 6 - 32 kí tự';
                    $flag = false;
                }
                if($validation->validPassword($password)) {
                    $this->view->passwordValue = $password;
                }
                else {
                    $this->view->errorPassword = 'Mật khẩu yêu cầu từ 6 - 32 kí tự';
                    $flag = false;
                }
                if($validation->validPassword($rePassword)) {
                    $this->view->rePasswordValue = $rePassword;
                }
                else {
                    $this->view->errorRePassword = 'Mật khẩu yêu cầu từ 6 - 32 kí tự';
                    $flag = false;
                }

                if($flag == true) {
                    $auth = Zend_Auth::getInstance();
                    $infoUser = $auth->getIdentity();
                    $user_id = $infoUser->user_id;
                    $checkPassword = $this->_model->checkPassword($user_id, $oldPassword);
                    if($checkPassword) {
                        if($password == $rePassword) {
                            $result = $this->_model->changePasswordUser($user_id, $password);
                            if($result) {
                                $this->view->error = 'Đổi mật khẩu thành công';
                            }
                            else {
                                $this->view->error = 'Có lỗi xảy ra';
                            }
                        }
                        else {
                            $this->view->error = 'Mật khẩu mới không trùng khớp';
                        }
                    }
                    else {
                        $this->view->error = 'Mật khẩu cũ không chính xác';
                    }
                }
            }
        }
    }
